package com.niiwoo.civet.trade.service.local.contract;

import com.niiwoo.civet.trade.dao.entity.FadadaContractTemplateFile;
import com.niiwoo.civet.trade.dao.entity.Project;
import com.niiwoo.civet.trade.dao.entity.ProjectContract;
import com.niiwoo.civet.trade.dao.entity.ProjectPackageInvestOrder;
import com.niiwoo.civet.trade.dao.mapper.FadadaContractTemplateFileMapperExt;
import com.niiwoo.civet.trade.enums.FadadaContractTemplateEnum;
import com.niiwoo.civet.trade.service.local.contract.vo.IntelligentContractDTO;
import com.niiwoo.tripod.base.component.PrivacyMasks;
import com.niiwoo.tripod.fadada.dto.request.GenerateContractRequestDTO;
import com.niiwoo.tripod.fadada.dto.response.FadadaResponseDTO;
import com.niiwoo.tripod.fadada.enums.SignClientRoleEnum;
import com.niiwoo.tripod.provider.exception.BizException;
import com.niiwoo.tripod.service.component.SnowflakeIdWorker;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 智能投服务协议
 *
 * @author liaojunjun
 */
@Service
public class IntelligentServiceProtocol extends AbstractFadadaContract {

    private static final Logger logger = LoggerFactory.getLogger(IntelligentServiceProtocol.class);

    @Value("${platform.caCertId}")
    private String platformCaCertId;

    @Autowired
    private PrivacyMasks privacyMasks;
    @Autowired
    private SnowflakeIdWorker snowflakeIdWorker;
    @Autowired
    private ContractBaseService contractBaseService;
    @Autowired
    private FadadaContractTemplateFileMapperExt contractTemplateFileMapperExt;

    @Override
    public ProjectContract contractHandler(FadadaContractTemplateFile contractTemplate, String bizContractNo,
                                           Project project, String userId) throws Exception {
        return null;
    }

    public ProjectContract contractHandler(FadadaContractTemplateEnum.TemplateTypeEnum templateType,
                                           ProjectPackageInvestOrder projectPackageInvestOrder, String investorUserId) throws Exception {
        logger.info("智能投服务协议处理开始... packageInvestOrderId:{}", projectPackageInvestOrder.getId());

        FadadaContractTemplateFile contractTemplate = contractTemplateFileMapperExt.queryFadadaContractTemplateFileByTemplateType(templateType.getType());
        // 借款合同模板不存在
        if (contractTemplate == null) {
            throw new BizException("TRD_700007", templateType + " templateType not exists.");
        }

        // 构建智能投风险提示书所需数据
        IntelligentContractDTO contractDTO = contractBaseService.buildIntelligenceContractDTO(investorUserId, projectPackageInvestOrder);

        this.generateContract(contractTemplate, contractDTO);

        ProjectContract result = this.signContract(contractTemplate, contractDTO);

        this.contractFilling(contractDTO.getContractId());

        logger.info("智能投服务协议处理结束... packageInvestOrderId:{}", projectPackageInvestOrder.getId());
        return result;
    }

    private void generateContract(FadadaContractTemplateFile contractTemplate, IntelligentContractDTO contractDTO) throws Exception {
        logger.info("智能投服务协议生成开始...packageInvestOrderId:{}", contractDTO.getPackageInvestOrderId());

        GenerateContractRequestDTO dto = new GenerateContractRequestDTO();
        dto.setContractId(contractDTO.getContractId());   //合同编号
        dto.setDocTitle(contractTemplate.getTemplateName());
        dto.setTemplateId(contractTemplate.getTemplateId());

        Map<String, String> parameterMap = new HashMap<String, String>();
        parameterMap.put("name", contractDTO.getUserName());
        parameterMap.put("idCard", privacyMasks.maskIdCardSixTwo(contractDTO.getIdCard()));
        parameterMap.put("signDate", DateFormatUtils.format(new Date(), "yyyy年MM月dd日"));
        parameterMap.put("finalSinName", contractBaseService.getFinalSinNameWithSpace(contractDTO.getUserName()));
        dto.setParameterMap(parameterMap);
        generateContract(dto);

        logger.info("智能投服务协议生成结束...packageInvestOrderId:{}", contractDTO.getPackageInvestOrderId());
    }

    private ProjectContract signContract(FadadaContractTemplateFile contractTemplate, IntelligentContractDTO contractDTO) throws Exception {
        logger.info("法大大合同自动签署-智能投服务协议 packageInvestOrderId:", contractDTO.getPackageInvestOrderId());

        // 委托方签署
        FadadaResponseDTO fadadaResponse = null;
        String docTitle = contractDTO.getUserName() + "的智能投服务协议_" + contractDTO.getContractId();
        String transactionId = snowflakeIdWorker.nextId() + "";
        String borrowerSignKeyword = contractBaseService.getFinalSinNameWithSpace(contractDTO.getUserName());
        fadadaResponse = extSignAuto(transactionId, contractDTO.getContractId(), contractDTO.getFadadaCacertId(),
                SignClientRoleEnum.BORROWER.getValue(), docTitle, borrowerSignKeyword);
        logger.info("法大大合同自动签署-智能投服务协议 借款人签署结束... packageInvestOrderId:{}", contractDTO.getPackageInvestOrderId());

        // 受托方签署
        transactionId = snowflakeIdWorker.nextId() + "";
        String guaranteeSignKeyword = "受托方（签章）：深圳市你我金融信息服务有限公司";
        fadadaResponse = extSignAuto(transactionId, contractDTO.getContractId(), platformCaCertId,
                SignClientRoleEnum.GUARANTEE.getValue(), docTitle, guaranteeSignKeyword);
        logger.info("法大大合同自动签署-智能投服务协议 担保公司签署结束... packageInvestOrderId:{}", contractDTO.getPackageInvestOrderId());

        return this.buildContractUpdateRecord(contractTemplate.getTemplateId(), contractDTO.getContractId(), transactionId,
                fadadaResponse.getViewUrl(), fadadaResponse.getDownloadUrl());
    }

}
